package com.adulcimer.core.config;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author Simon
 * @create 2025/7/29
 * @Description
 **/
@Configuration
@EnableTransactionManagement
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        paginationInnerInterceptor.setOptimizeJoin(true);
        paginationInnerInterceptor.setDbType(DbType.MYSQL);
        paginationInnerInterceptor.setOverflow(true);
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        return interceptor;
    }


    /**
     * 添加自动填充插件
     * 这个 Bean 会被 MyBatis-Plus 自动识别并用于填充字段
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                //当数据库服务器时间与代码服务器时间不一致时选择
//                LocalDateTime now = LocalDateTime.now();
                Long currentUser = getCurrentUser();

                // 当字段为空时填充
                this.strictInsertFill(metaObject, "createdBy", Long.class, currentUser);
//                this.strictInsertFill(metaObject, "createdTime", LocalDateTime.class, now);
                this.strictInsertFill(metaObject, "updatedBy", Long.class, currentUser);
//                this.strictInsertFill(metaObject, "updatedTime", LocalDateTime.class, now);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
//                LocalDateTime now = LocalDateTime.now();
                Long currentUser = getCurrentUser();

                this.strictUpdateFill(metaObject, "updatedBy", Long.class, currentUser);
//                this.strictUpdateFill(metaObject, "updatedTime", LocalDateTime.class, now);
            }
        };
    }
    private Long getCurrentUser() {
        return StpUtil.getLoginIdAsLong();
    }
}